"""
Browser manager for handling browser operations
"""
import random
import time
from playwright.sync_api import sync_playwright
from config.browser_config import (
    BROWSER_ARGS,
    USER_AGENTS,
    CONTEXT_SETTINGS,
    STEALTH_SCRIPTS,
    TIMEOUT_SETTINGS,
    DELAY_SETTINGS
)

class BrowserManager:
    def __init__(self):
        self.playwright = None
        self.browser = None
        self.context = None
        self.page = None

    def __enter__(self):
        self.playwright = sync_playwright().start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def launch_browser(self):
        """Launch browser with configured settings"""
        self.browser = self.playwright.chromium.launch(
            headless=True,
            args=BROWSER_ARGS
        )
        return self

    def create_context(self):
        """Create browser context with configured settings"""
        context_settings = CONTEXT_SETTINGS.copy()
        context_settings['user_agent'] = random.choice(USER_AGENTS)
        
        self.context = self.browser.new_context(**context_settings)
        return self

    def create_page(self):
        """Create new page and inject stealth scripts"""
        self.page = self.context.new_page()
        
        # Set default timeout
        self.page.set_default_timeout(TIMEOUT_SETTINGS['default_timeout'])
        
        # Inject stealth scripts
        for script in STEALTH_SCRIPTS:
            self.page.add_init_script(script)
            
        return self

    def random_delay(self):
        """Add random delay between actions"""
        time.sleep(random.uniform(
            DELAY_SETTINGS['min_delay'],
            DELAY_SETTINGS['max_delay']
        ))

    def navigate(self, url):
        """Navigate to URL with configured settings"""
        print(f"Navigating to {url}")
        response = self.page.goto(
            url,
            wait_until='domcontentloaded',
            timeout=TIMEOUT_SETTINGS['navigation_timeout']
        )
        print(f"Navigation response status: {response.status}")
        return response

    def wait_for_content(self):
        """Wait for page content to be ready"""
        print("Waiting for page to load...")
        self.page.wait_for_load_state(
            'domcontentloaded',
            timeout=TIMEOUT_SETTINGS['default_timeout']
        )
        
        print("Waiting for content to be visible...")
        self.page.wait_for_selector(
            'body',
            timeout=TIMEOUT_SETTINGS['wait_for_selector_timeout']
        )
        
        print(f"Waiting for {DELAY_SETTINGS['final_wait']} seconds to ensure complete loading...")
        time.sleep(DELAY_SETTINGS['final_wait'])

    def get_content(self):
        """Get page content"""
        return self.page.content()

    def close(self):
        """Close browser and cleanup"""
        if self.context:
            self.context.close()
        if self.browser:
            self.browser.close()
        if self.playwright:
            self.playwright.stop() 